package org.example.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhengdp
 * @Description 定时任务执行
 * @Date 2022/12/20 21:29
 * @Created by zhengdp
 */
@Slf4j(topic = "c.TestSchedule")
public class TestSchedule {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取本周四时间 (需要判断当前时间是否大于周四）
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        if(now.compareTo(time) > 0){
            time = time.plusWeeks(1);
        }
        // 当前时间与周四18点的时间差
        long initDelay = Duration.between(now, time).toMillis();
        // 每周的时间间隔
        long period = 1000 * 60 * 60 * 24 * 7;
        pool.scheduleAtFixedRate(() -> {
            System.out.println("running ...");
        },initDelay,period, TimeUnit.SECONDS);
    }
}
